<template>
  <el-row class="home" :gutter="20">
    <el-col :span="8" style="margin-top: 20px; " class="user-order-info">
      <el-card shadow="hover">
        <div class="user">
          <img :src="getImageUrl()" class="user" />
          <div class="user-info">
            <p class="user-info-admin">Admin</p>
            <p class="user-info-role">超级管理员</p>
          </div>
        </div>
        <div class="login-info">
          <p>上次登录时间：<span>2021-09-01 10:00:00</span></p>
          <p>上次登录地点：<span>惠州</span></p>
        </div>
      </el-card>
      <el-card shadow="hover" class="user-table">
        <el-table :data="tableData">
          <el-table-column v-for="(val, key) in tableLabel" :key="key" :prop="key" :label="val"></el-table-column>
        </el-table>
      </el-card>
    </el-col>
    <el-col :span="16" style="margin-top: 20px">
      <div class="num">
        <el-card v-for="item in countData" :key="item.name" :body-style="{ display: 'flex', padding: 0 }" class="num-card">          <component :is="item.icon" class="icons" :style="{ background: item.color }" />
          <div class="detail">
            <p class="price">￥{{ item.value }}</p>
            <p class="desc">{{ item.name }}</p>
          </div>
        </el-card>
      </div>
      <el-card shadow="hover" class="top-echart">
        <div ref="echart" style="height: 280px"></div>
      </el-card>
      <div class="graph">
        <el-card shadow="hover">
          <div ref="userEchart" style="height: 240px"></div>
        </el-card>
        <el-card shadow="hover">
          <div ref="videpEchart" style="height: 240px"></div>
        </el-card>
      </div>
    </el-col>
  </el-row>
</template>

<script setup>
import { ref, getCurrentInstance, onMounted, reactive } from "vue";
import * as echarts from "echarts";
// 引入需要用到的图标组件
import { Tickets, Star, DocumentRemove, Document, Collection } from "@element-plus/icons-vue";

const { proxy } = getCurrentInstance();
const getImageUrl = () => {
  return new URL(`../assets/images/user.png`, import.meta.url).href;
};

const tableData = ref([]);

const countData = ref([]);

const chartData = ref([]);

const observer = ref(null);

const tableLabel = ref({
  name: "球场名称",
  todayBuy: "今日购买",
  monthBuy: "本月购买",
  totalBuy: "总购买",
});

//这个是折线图和柱状图 两个图表共用的公共配置
const xoptions = reactive({
  // 图例文字颜色
  textStyle: {
    color: "#333",
  },
  legend: {},
  grid: {
    left: "20%",
  },
  // 提示框
  tooltip: {
    trigger: "axis",
  },
  xAxis: {
    type: "category", // 类目轴
    data: [],
    axisLine: {
      lineStyle: {
        color: "#17b3a3",
      },
    },
    axisLabel: {
      interval: 0,
      color: "#333",
    },
  },
  yAxis: [
    {
      type: "value",
      axisLine: {
        lineStyle: {
          color: "#17b3a3",
        },
      },
    },
  ],
  color: ["#2ec7c9", "#b6a2de", "#5ab1ef", "#ffb980", "#d87a80", "#8d98b3"],
  series: [],
});

const pieOptions = reactive({
  tooltip: {
    trigger: "item",
  },
  legend: {},
  color: [
    "#0f78f4",
    "#dd536b",
    "#9462e5",
    "#a6a6a6",
    "#e1bb22",
    "#39c362",
    "#3ed1cf",
  ],
  series: []
});

/**
 * 异步获取表格数据并更新组件状态
 * 调用API服务获取数据，将返回的tableData赋值给响应式引用以触发视图更新
 * 同时输出原始数据到控制台用于调试
 * 
 * @returns {Promise<void>} 无返回值，通过tableData响应式引用更新数据
 */
const getTableData = async () => {
  try {
    const res = await proxy.$api.getTableData();
    // 根据API拦截器，res已经是data部分，而mock数据中tableData在res.tableData中
    tableData.value = res.tableData || [];
  } catch (error) {
    console.error("获取表格数据失败:", error);
  }
};

const getCountData = async () => {
  try {
    const res = await proxy.$api.getCountData();
    // 根据API拦截器，res已经是data部分，而mock数据中countData在res.countData中
    countData.value = res.countData || [];
  } catch (error) {
    console.error("获取统计数据失败:", error);
  }
};

const getChartData = async () => {
  try {
    const { orderData, userData, videoData } = await proxy.$api.getChartData();
    // 对第一个图标进行x轴和series赋值
    xoptions.xAxis.data = orderData.date;
    xoptions.series = Object.keys(orderData.data[0]).map(val => {
      return {
        name: val,
        type: "line",
        data: orderData.data.map(item => item[val]),
      };
    });
    const oneEchart = echarts.init(proxy.$refs['echart']);
    oneEchart.setOption(xoptions);

    // 对第二个图标进行渲染
    xoptions.xAxis.data = userData.map(item => item.date)
    xoptions.series = [
      {
        name: "新增用户",
        type: "bar",
        data: userData.map(item => item.new),
      },
      {
        name: "活跃用户",
        type: "bar",
        data: userData.map(item => item.active),
      }
    ]
    const twoEchart = echarts.init(proxy.$refs['userEchart'])
    twoEchart.setOption(xoptions)

    // 对饼状图进行渲染
    pieOptions.series = [
      {
        data: videoData,
        type: 'pie'
      }
    ]
    const pieEchart = echarts.init(proxy.$refs['videpEchart'])
    pieEchart.setOption(pieOptions)

    // 监听页面的变化
    observer.value = new ResizeObserver((en) => {
      oneEchart.resize()
      twoEchart.resize()
      pieEchart.resize()
    })

    // 容器存在
    if (proxy.$refs['echart']) {
      observer.value.observe(proxy.$refs['echart'])
    }
  } catch (error) {
    console.error("获取图表数据失败:", error);
  }
};

onMounted(() => {
  getTableData();
  getCountData();
  getChartData();
});
</script>

<style scoped lang="less">
.home {
  height: 100%;
  overflow: hidden;

  .user {
    display: flex;
    align-items: center;
    border-bottom: 1px solid #ccc;
    margin-bottom: 20px;

    img {
      width: 150px;
      height: 150px;
      border-radius: 50%;
      margin-right: 40px;
    }

    .user-info {
      p {
        line-height: 40px;
      }

      .user-info-role {
        color: #999;
      }

      .user-info-admin {
        font-size: 35px;
      }
    }
  }

  .login-info {
    p {
      line-height: 1.5;
      font-family: "楷体", "KaiTi", "STKaiti", cursive;
      font-size: 16px;
      color: #999;

      span {
        color: #666;
        margin-left: 10px;
      }
    }
  }

  .user-table {
    margin-top: 20px;
  }

  .num {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;

    .el-card {
      width: 32%;
      margin-bottom: 20px;
      height: 80px;


      .icons {
        width: 80px;
        height: 80px;
        font-size: 30px;
        text-align: center;
        line-height: 80px;
        color: white;

      }

      .detail {
        margin-left: 15px;
        display: flex;
        flex-direction: column;
        justify-content: center;

        .price {
          font-size: 30px;
          margin-top: 4px;
          margin-bottom: 4px;
        }

        .desc {
          margin-top: 0px;
          font-size: 15px;
          text-align: center;
          color: #999;
        }
      }
    }
  }
  .graph {
    margin-top: 20px;
    display: flex;
    justify-content: space-between;
    .el-card{
      width: 48%;
      height: 260px;
    }
  }
}
</style>